package com.cloud.common.support;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class DateConverter implements Converter<String, Date> {
    private static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
    private static final String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    @Override
    public Date convert(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        dateStr = dateStr.trim();
        try {
            if (dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
                return new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD).parse(dateStr);
            }
            if (dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                return new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD_HH_MM_SS).parse(dateStr);
            }
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}